<script lang="ts" setup name="storeProcessFlowStep">
import { ref, reactive, onMounted, onUnmounted, computed, nextTick, watch } from 'vue';
import { auth } from '/@/utils/authFunction';
import { ElMessageBox, ElMessage } from 'element-plus';
import { downloadStreamFile } from '/@/utils/download';
import { useStoreProcessFlowStepApi } from '/@/api/store/storeProcessFlowStep';
import { useUserInfo } from '/@/stores/userInfo';
import { getAPI } from '/@/utils/axios-utils';
import { useStoreBudgetConfigApi } from '/@/api/store/storeBudgetConfig';
import editDialog from '/@/views/store/storeProcessFlowStep/component/editDialog.vue';
import approvalDialog from '/@/views/store/storeProcessFlowStep/component/approvalDialog.vue';
import detailDialog from '/@/views/store/storeProcessFlowStep/component/detailDialog.vue';
import batchApprovalDialog from '/@/views/store/storeProcessFlowStep/component/batchApprovalDialog.vue';
import printDialog from '/@/views/system/print/component/hiprint/preview.vue';
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import StoreTypeTree from '/@/views/store/storeMaterials/component/storeTypeTree.vue';
import { SysOrgApi } from '/@/api-services/api';
import type { SysOrg } from '/@/api-services/models/sys-org';
import OrgTree from '/@/views/system/org/component/orgTree.vue';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';

const storeProcessFlowStepApi = useStoreProcessFlowStepApi();
const userInfoStore = useUserInfo();
const storeBudgetConfigApi = useStoreBudgetConfigApi();

const SYSTEM_ADMIN_ACCOUNT_TYPES = [888, 999];

// 当前用户信息
const currentUser = computed(() => userInfoStore.userInfos);

const isSystemAdminAccount = computed(() => {
	const type = Number(currentUser.value?.accountType ?? 0);
	return SYSTEM_ADMIN_ACCOUNT_TYPES.includes(type);
});

// 批量审批按钮显示控制
const showBatchApprovalButton = computed(() => {
	if (state.activeTab === 'myPending') {
		return true;
	}
	if (state.activeTab === 'allApprovals') {
		// 仅系统管理员账户在“全部审批”支持批量操作
		return isSystemAdminAccount.value;
	}
	return false;
});

const printDialogRef = ref();
const editDialogRef = ref();
const approvalDialogRef = ref();
const detailDialogRef = ref();
const batchApprovalDialogRef = ref();
const storeTypeTreeRef = ref();
const orgOptions = ref<SysOrg[]>([]);
const orgTreeRef = ref();
// 防止批量提交重复执行
const isBatchSubmitting = ref(false);
const isActionLocked = computed(() => state.tableLoading || isBatchSubmitting.value);

const state = reactive({
	exportLoading: false,
	tableLoading: false,
	stores: {},
	showAdvanceQueryUI: false, // 高级查询展开状态
	dropdownData: {} as any,
	selectData: [] as any[],
	activeTab: 'myPending', // 当前激活的tab：myPending 或 allApprovals
	storeTypeTreeData: [] as any[], // 物资分类树数据
	currentCategoryId: 0, // 当前选中的分类ID，0表示全部
	tableQueryParams: {} as any,
	tableParams: {
		page: 1,
		pageSize: 20,
		total: 0,
		field: 'createTime', // 默认的排序字段
		order: 'descending', // 排序方向
		descStr: 'descending', // 降序排序的关键字符
	},
	tableData: [],
	budgetInfo: null as any, // 预算信息
	budgetLoading: false, // 预算加载状态
});

interface FlowStep {
	title: string;
	short: string;
}

interface FlowMeta {
	steps: FlowStep[];
	statuses: string[];
	connectors: boolean[];
	tooltips: string[];
	summary: string;
}

const stageNameMap: Record<string, string> = {
	审核: '待审核',
	审批: '待审批',
	发放: '待发放',
};

const FLOW_STEPS_BY_TYPE: Record<string, FlowStep[]> = {
	入库: Object.freeze([
		{ title: '申请', short: '申' },
		{ title: '审核', short: '核' },
		{ title: '审批', short: '批' },
		{ title: '发放', short: '放' },
		{ title: '完成', short: '完' },
	]),
	出库: Object.freeze([
		{ title: '申请', short: '申' },
		{ title: '审核', short: '核' },
		{ title: '审批', short: '批' },
		{ title: '发放', short: '放' },
		{ title: '完成', short: '完' },
	]),
};

const resolveFlowStepsByType = (flowType: string): FlowStep[] => FLOW_STEPS_BY_TYPE[flowType] || FLOW_STEPS_BY_TYPE['入库'];


// 页面加载时
const loadOrgOptions = async () => {
	try {
		const res = await getAPI(SysOrgApi).apiSysOrgListGet(0, undefined, undefined, undefined, undefined);
		// 筛选第二级区域数据（作业区）- 这些区域的 pid 是第一级部门的 id
		const allOrgs = (res.data.result || []) as SysOrg[];
		const topLevel = allOrgs.find((org: SysOrg) => Number(org.pid) === 0); // 找到第一级部门
		if (topLevel && topLevel.children) {
			// 从第一级部门的children中获取第二级区域
			orgOptions.value = topLevel.children.filter((org: SysOrg) => org.level === 2) || [];
		} else {
			// 备选方案：直接从扁平列表中筛选 level 为 2 的数据
			orgOptions.value = allOrgs.filter((org: SysOrg) => org.level === 2) || [];
		}
	} catch (error) {
		console.error('加载区域数据失败:', error);
	}
};

const computeDefaultTableHeight = () => {
	if (typeof window === 'undefined') return 600;
	return Math.max(window.innerHeight - 360, 320);
};

// 计算表格卡片最小高度 - 基于 tabs-card 的实际高度
const tableCardMinHeight = ref('calc(100% - 150px)');
const tableHeight = ref<number>(computeDefaultTableHeight());
let resizeListener: (() => void) | null = null;
let resizeRaf = 0;

const updateTableHeight = () => {
	if (typeof window === 'undefined') return;
	tableHeight.value = computeDefaultTableHeight();
};

const calculateTableCardMinHeight = () => {
	const tabsCardEl = document.querySelector('.tabs-card');

	if (!tabsCardEl) {
		// 如果还没渲染，延迟执行
		nextTick(() => {
			calculateTableCardMinHeight();
		});
		return;
	}

	// 获取 tabs-card 的实际高度
	const tabsCardHeight = tabsCardEl.clientHeight;
	// table-card 的最小高度 = 100% - tabs-card高度
	tableCardMinHeight.value = `calc(100% - ${tabsCardHeight + 25}px)`;
};

const handleResize = () => {
	if (resizeRaf) {
		cancelAnimationFrame(resizeRaf);
	}
	resizeRaf = requestAnimationFrame(() => {
		calculateTableCardMinHeight();
		updateTableHeight();
	});
};

onMounted(async () => {
	await loadStoreTypeTree();
	await loadOrgOptions();
	handleQuery();

	// 延迟计算表格卡片高度，基于 tabs-card 的实际高度
	setTimeout(() => {
		calculateTableCardMinHeight();
		updateTableHeight();
		resizeListener = handleResize;
		window.addEventListener('resize', resizeListener);
	}, 300);
});

onUnmounted(() => {
	// 清理resize事件监听器
	if (resizeListener) {
		window.removeEventListener('resize', resizeListener);
		resizeListener = null;
	}
	if (resizeRaf) {
		cancelAnimationFrame(resizeRaf);
		resizeRaf = 0;
	}
});

// 监听高级查询展开/收起，自动重新计算表格高度
watch(
	() => state.showAdvanceQueryUI,
	() => {
		// 等待DOM更新完成后，重新计算高度
		nextTick(() => {
			setTimeout(() => {
				calculateTableCardMinHeight();
				updateTableHeight();
			}, 50);
		});
	}
);

// 加载物资分类树数据
const loadStoreTypeTree = async () => {
	try {
		const data = (await storeProcessFlowStepApi.getStoreTypeDropdownData({ fromPage: true }).then((res) => res.data.result)) ?? {};
		state.dropdownData.storeTypeId = data.pid || [];
		state.storeTypeTreeData = data.pid || [];
	} catch (error) {
		console.error('加载物资分类树失败:', error);
		ElMessage.error('加载物资分类失败');
	}
};

// 分类节点点击事件
const handleCategoryChange = (node: any) => {
	const nodeId = node.id || node.value || 0;
	state.currentCategoryId = nodeId;
	state.tableParams.page = 1;
	if (nodeId === 0 || nodeId === '0') {
		delete state.tableQueryParams.storeTypeId;
	} else {
		state.tableQueryParams.storeTypeId = nodeId;
	}
	handleQuery();
};

// Tab切换
const handleTabChange = (tabName: string) => {
	state.activeTab = tabName;

	// 重置所有状态
	state.tableParams = {
		page: 1,
		pageSize: 20,
		total: 0,
		// “全部审批”默认按更新时间(近的在前)排序，方便刚审批完立即核对
		field: tabName === 'allApprovals' ? 'updateTime' : 'createTime',
		order: 'descending',
		descStr: 'descending',
	};

	state.selectData = []; // 清空选择
	state.tableQueryParams = tabName === 'allApprovals' ? { includeArchived: false } : {}; // 清空查询参数，按Tab设置归档过滤
	state.currentCategoryId = 0; // 重置分类选择

	// 延迟一下再查询，确保状态更新完成
	nextTick(() => {
		storeTypeTreeRef.value?.setCurrentKey(0); // 重置树选中状态
		handleQuery();
		// 重新计算表格卡片高度
		calculateTableCardMinHeight();
		updateTableHeight();
	});
};

// 查询操作
// 导出数据操作
const exportStoreProcessFlowStepCommand = async (command: string) => {
	try {
		state.exportLoading = true;
		let params;
		if (command === 'select') {
			params = Object.assign({}, state.tableQueryParams, state.tableParams, { selectKeyList: state.selectData.map((u) => u.id) });
		} else if (command === 'current') {
			params = Object.assign({}, state.tableQueryParams, state.tableParams);
		} else if (command === 'all') {
			params = Object.assign({}, state.tableQueryParams, state.tableParams, { page: 1, pageSize: 99999999 });
		}

		// 根据当前tab决定是否添加用户过滤
		if (state.activeTab === 'myPending') {
			// 待我审批：传入当前用户ID
			params.currentUserId = currentUser.value.id;
		}

		await storeProcessFlowStepApi.exportData(params).then((res) => downloadStreamFile(res));
	} finally {
		state.exportLoading = false;
	}
};

const handleQuery = async (params: any = {}) => {
	state.tableLoading = true;
	state.tableParams = Object.assign(state.tableParams, params);

	const queryParams = {
		...state.tableQueryParams,
		...state.tableParams,
	};

	// 根据当前tab决定是否添加用户过滤
	if (state.activeTab === 'myPending') {
		// 待我审批：传入当前用户ID
		queryParams.currentUserId = currentUser.value.id;
		delete queryParams.includeArchived;
	} else {
		// 全部审批默认不包含归档数据，除非显式传入
		queryParams.includeArchived = Boolean(queryParams.includeArchived);
	}
	// 全部审批：不传入currentUserId，显示所有记录

	const result = await storeProcessFlowStepApi.page(queryParams).then((res) => res.data.result);
	state.tableParams.total = result?.total;
	const items = result?.items ?? [];
	items.forEach((item: any) => {
		item.__flowMeta = computeFlowMeta(item);
	});
	state.tableData = items;
	state.tableLoading = false;
	nextTick(() => {
		updateTableHeight();
	});
};

// 区域选择处理
const handleOrgChange = (node: any) => {
	const nodeId = node.id || node.value || null;
	state.tableQueryParams.orgId = nodeId;
	state.tableParams.page = 1;
	handleQuery();
};

// 重置区域树
const resetOrgTree = () => {
	orgTreeRef.value?.initTreeData();
};

// 列排序
const sortChange = async (column: any) => {
	state.tableParams.field = column.prop;
	state.tableParams.order = column.order;
	await handleQuery();
};

// 删除
const delStoreProcessFlowStep = (row: any) => {
	const isCompleted = row.approvalAction === 4 && row.completedTime;
	const confirmMessage = isCompleted ? `确定要删除这个${row.flowType}审批流程吗？\n\n⚠️ 此操作将自动撤回已完成的库存变更并做记录。` : `确定要删除这个${row.flowType}审批流程吗？`;

	ElMessageBox.confirm(confirmMessage, '删除确认', {
		confirmButtonText: '确定删除',
		cancelButtonText: '取消',
		type: 'warning',
		dangerouslyUseHTMLString: false,
	})
		.then(async () => {
			await storeProcessFlowStepApi.delete({ id: row.id });
			handleQuery();
			ElMessage.success(isCompleted ? '删除成功，库存已自动撤回' : '删除成功');
		})
		.catch(() => {});
};

// 批量删除
const batchDelStoreProcessFlowStep = () => {
	ElMessageBox.confirm(`确定要删除${state.selectData.length}条记录吗?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await storeProcessFlowStepApi.batchDelete(state.selectData.map((u) => ({ id: u.id }))).then((res) => {
				ElMessage.success(`成功批量删除${res.data.result}条记录`);
				handleQuery();
			});
		})
		.catch(() => {});
};

// 获取状态标签类型
const getStatusTagType = (status: number) => {
	switch (status) {
		case 1:
			return 'info'; // 待审核
		case 2:
			return 'warning'; // 已审核
		case 3:
			return 'success'; // 已审批
		case 4:
			return 'success'; // 已完成
		case 5:
			return 'danger'; // 已拒绝
		default:
			return 'info';
	}
};

// 获取审批操作标签类型
const getApprovalTagType = (approvalAction: number) => {
	switch (approvalAction) {
		case 1:
			return 'info'; // 待审核
		case 2:
			return 'warning'; // 已审核
		case 3:
			return 'success'; // 已审批
		case 4:
			return 'success'; // 已完成
		case 5:
			return 'danger'; // 已拒绝
		default:
			return 'info';
	}
};

// 获取审批操作标签文本
const getApprovalTagText = (approvalAction: number) => {
	switch (approvalAction) {
		case 1:
			return '待审核';
		case 2:
			return '已审核';
		case 3:
			return '已审批';
		case 4:
			return '已完成';
		case 5:
			return '已拒绝';
		default:
			return '未知状态';
	}
};

// 审批操作
const handleApproval = (row: any, approvalAction?: number) => {
	if (isActionLocked.value) {
		ElMessage.warning('正在处理中，请稍候');
		return;
	}
	// 检查行数据完整性
	if (!row || !row.id) {
		ElMessage.error('审批数据不完整，请刷新页面后重试');
		return;
	}

	const action = approvalAction === 5 ? 'reject' : 'approve';
	approvalDialogRef.value?.openDialog(row, action);
};


const handleReturn = (row: any) => {
	if (isActionLocked.value) {
		ElMessage.warning('正在处理中，请稍候');
		return;
	}
	if (!row || !row.id) {
		ElMessage.error('退回数据不完整，请刷新页面后重试');
		return;
	}

	ElMessageBox.prompt('请输入退回原因（可选）', '退回确认', {
		confirmButtonText: '确认退回',
		cancelButtonText: '取消',
		inputPlaceholder: '请输入退回原因（最多255个字符）',
		inputType: 'textarea',
		inputValue: '',
		inputValidator: (value: string) => {
			if (value && value.length > 255) {
				return '退回原因长度不能超过255个字符';
			}
			return true;
		},
	})
		.then(async ({ value }: { value: string }) => {
			const normalizedReason = value.trim();
			const payload = {
				id: row.id,
				reason: normalizedReason ? normalizedReason : undefined,
			};
			await storeProcessFlowStepApi.returnPreviousStep(payload);
			ElMessage.success('已退回至上一步');
			handleQuery();
		})
		.catch(() => {});
};

// 处理审批提交
const handleApprovalSubmit = async (formData: any) => {
	try {
		const actionText = formData.action === 'approve' ? '同意' : '拒绝';
		const approvalData = formData.originalData;

		if (!approvalData || !approvalData.id) {
			ElMessage.error('审批数据获取失败，请重新打开审批弹窗');
			return;
		}

		const allowAdminDirectApprove =
			formData.action === 'approve'
				? approvalData?.canAdminDirectApprove ?? legacyCanDirectApprove(approvalData)
				: false;

		if (allowAdminDirectApprove && !formData.confirmerId) {
			ElMessage.error('系统管理员直接审批时必须指定发放确认人');
			return;
		}

		const computedNextStatus =
			formData.action === 'approve'
				? approvalData?.nextApprovalAction ?? legacyGetNextApprovalStatus(approvalData)
				: 5;

		if (formData.action === 'approve' && (computedNextStatus === undefined || computedNextStatus === null)) {
			ElMessage.error('当前审批节点已无法继续推进，请刷新后重试');
			return;
		}

		const nextStatus = computedNextStatus ?? approvalData.approvalAction;

		const nextQuantity = formData.action === 'approve' ? formData.approvedQuantity || approvalData.quantity : approvalData.quantity;
		const normalizedQuantity = nextQuantity !== undefined && nextQuantity !== null ? Number(nextQuantity) : nextQuantity;
		const recalculatedTotal = formData.action === 'approve' ? calculateMaterialTotal(approvalData, normalizedQuantity as number | undefined) : approvalData.materialPriceTotal;

		// 构建更新数据 - 后端会自动处理确认人和步骤推进
		const updateData = {
			id: approvalData.id,
			flowType: approvalData.flowType,
			batchNo: approvalData.batchNo,
			requestNo: approvalData.requestNo,
			storeTypeId: approvalData.storeTypeId,
			storeTypeName: approvalData.storeTypeName,
			materialId: approvalData.materialId,
			materialName: approvalData.materialName,
			materialPrice: approvalData.materialPrice,
			quantity: normalizedQuantity,
			unit: approvalData.unit,
			materialPriceTotal: recalculatedTotal,
			applicantId: approvalData.applicantId,
			applicantName: approvalData.applicantName,
			applicantDept: approvalData.applicantDept,
			receiverId: approvalData.receiverId,
			receiverName: approvalData.receiverName,
			receiverDept: approvalData.receiverDept,
			requestTime: approvalData.requestTime,
			expectedDate: approvalData.expectedDate,
			completedTime: approvalData.completedTime,
			statusNewOrChange: approvalData.statusNewOrChange,
			approvalAction: nextStatus, // 后端根据状态推进至下一步
			remark: formData.remark || `${actionText}审批`,
			// 后端会自动处理确认人和步骤推进，前端只需要传递当前操作的确认人信息
			confirmerId: formData.confirmerId || null,
			confirmerName: formData.confirmerName || '',
			adminDirectApprove: allowAdminDirectApprove || undefined,
		};

	// 调用更新API
	await storeProcessFlowStepApi.update(updateData);

	ElMessage.success(`${actionText}成功`);

	// 刷新列表
	// 审批后切换到按“更新时间”降序，方便核对最新审批记录
	const refreshParams = state.activeTab === 'allApprovals'
		? { field: 'updateTime', order: 'descending' }
		: {};
	handleQuery(refreshParams);
} catch (error) {
	const actionText = formData.action === 'approve' ? '同意' : '拒绝';
	ElMessage.error(`${actionText}失败，请重试`);
}
};

// 获取显示的总步数
const getDisplayTotalSteps = (row: any) => {
	// 如果数据中的totalSteps不正确，根据流程类型返回正确的步数
	if (row.flowType === '入库') {
		return 3;
	} else if (row.flowType === '出库') {
		return 4;
	}
	return row.totalSteps || 2;
};

// 获取显示的当前步骤
const getDisplayCurrentStep = (row: any) => {
	// 如果已完成，显示最后一步
	if (row.approvalAction === 4) {
		// 已完成
		return getDisplayTotalSteps(row);
	}
	// 否则返回实际的当前步骤
	return row.currentStep || 1;
};

// 判断是否应该显示审批按钮
const legacyCanReturnToPreviousStep = (row: any) => {
	if (!row) return false;
	const approvalAction = Number(row.approvalAction ?? 0);
	const currentStep = Number(row.currentStep ?? 0);
	if (approvalAction === 4 || approvalAction === 5) return false;
	if (currentStep <= 1) return false;

	if (row.flowType === '入库') {
		return currentStep === 2;
	}

	if (row.flowType === '出库') {
		return currentStep === 2 || currentStep === 3;
	}

	return false;
};
const legacyGetNextApprovalStatus = (row: any) => {
	const approvalAction = Number(row.approvalAction ?? 0);
	if (approvalAction === 1) {
		return row.flowType === '出库' ? 2 : 3;
	}

	if (approvalAction === 2 && row.flowType === '出库') return 3;

	if (approvalAction === 3) return 4;

	return 3;
};

const legacyCanDirectApprove = (row: any) => {
	if (!row || !isSystemAdminAccount.value) return false;
	if (row.flowType !== '出库') return false;
	const approvalAction = Number(row.approvalAction ?? 0);
	const currentStep = Number(row.currentStep ?? 1);
	return approvalAction === 1 || (approvalAction === 2 && currentStep <= 2);
};

const resolveOperationFlags = (row: any) => {
	const target = row ?? {};
	const hasMeta =
		'canApprove' in target ||
		'canReject' in target ||
		'canReturn' in target;

	if (hasMeta) {
		return {
			canApprove: Boolean(row?.canApprove),
			canReject: Boolean(row?.canReject),
			canReturn: Boolean(row?.canReturn),
		};
	}

	const approvalAction = Number(row?.approvalAction ?? 0);
	const currentStep = Number(row?.currentStep ?? 1);
	const flowType = row?.flowType ?? '';
	const isConfirmer = row?.confirmerId === currentUser.value?.id;
	const canOperateBase = isConfirmer || isSystemAdminAccount.value;

	const canApprove =
		canOperateBase &&
		(approvalAction === 1 ||
			(flowType === '入库' && approvalAction === 3 && currentStep === 2) ||
			(flowType === '出库' && (approvalAction === 2 || (approvalAction === 3 && currentStep === 3))));

	const canReject = canOperateBase && approvalAction > 0 && approvalAction < 5;
	const canReturn = canOperateBase && legacyCanReturnToPreviousStep(row);

	return { canApprove, canReject, canReturn };
};

const shouldShowApprovalButtons = (row: any) => {
	const { canApprove, canReject } = resolveOperationFlags(row);
	return Boolean(canApprove || canReject);
};


const canReturnToPreviousStep = (row: any) => {
	const { canReturn } = resolveOperationFlags(row);
	return Boolean(canReturn);
};

const calculateMaterialTotal = (row: any, quantity: number | null | undefined) => {
	const unitPrice = Number(row?.materialPrice ?? 0);
	const originalTotal = Number(row?.materialPriceTotal ?? 0);
	if (quantity === null || quantity === undefined) {
		return originalTotal || row?.materialPriceTotal;
	}
	if (Number.isNaN(unitPrice)) {
		return originalTotal || row?.materialPriceTotal;
	}
	const safeQuantity = Number(quantity);
	if (Number.isNaN(safeQuantity)) {
		return originalTotal || row?.materialPriceTotal;
	}
	return Number((unitPrice * safeQuantity).toFixed(2));
};

const totalAmount = computed(() => {
	return state.tableData.reduce((total: number, item: any) => total + (item.materialPriceTotal || 0), 0);
});

const selectedAmount = computed(() => {
	return state.selectData.reduce((total: number, item: any) => total + (item.materialPriceTotal || 0), 0);
});

const enableVirtualScroll = computed(() => state.tableData.length > 40);

const getApprovalButtonText = (row: any) => {
	return '同';
};

const getRejectButtonText = (row: any) => {
	return '拒';
};

const getReturnButtonText = (row: any) => {
	return '退';
};

// 获取步骤描述文本
const getStepText = (row: any) => {
	const approvalAction = row.approvalAction;
	const isInbound = row.flowType === '入库';
	const isOutbound = row.flowType === '出库';

	// 根据当前状态返回描述
	switch (approvalAction) {
		case 1: // 待审核
			return isInbound ? '待部门主管审核' : '待区域主管审核';
		case 2: // 已审核
			return isInbound ? '待部门物资负责人审批' : '待部门主管审批';
		case 3: // 已审批
			return isInbound ? '待发放入库' : '待部门物资负责人审查';
		case 4: // 已完成
			return isInbound ? '入库完成' : isOutbound ? '出库完成' : '已完成';
		case 5: // 已拒绝
			return '审批被拒绝';
		default:
			return '待处理';
	}
};

// 获取表格中的流程步骤
const getTableFlowSteps = (row: any): FlowStep[] => resolveFlowStepsByType(row.flowType);

const computeFlowMeta = (row: any): FlowMeta => {
	const steps = getTableFlowSteps(row);
	const stepCount = steps.length;
	const statuses = new Array(stepCount).fill('wait');
	const tooltips = new Array(stepCount).fill('');
	const connectors = new Array(Math.max(stepCount - 1, 0)).fill(false);

	const approvalAction = Number(row?.approvalAction ?? 1);
	const isInbound = row.flowType === '入库';
	const isOutbound = row.flowType === '出库';
	const processSteps = Array.isArray(row.processSteps) ? row.processSteps : null;

	let completedStep = 1;
	let activeStep = Math.min(2, stepCount);
	let rejectStep = 0;

	switch (approvalAction) {
		case 1:
			completedStep = 1;
			activeStep = Math.min(2, stepCount);
			break;
		case 2:
			completedStep = 2;
			activeStep = Math.min(3, stepCount);
			break;
		case 3:
			completedStep = 3;
			activeStep = Math.min(4, stepCount);
			break;
		case 4:
			completedStep = stepCount;
			activeStep = stepCount;
			break;
		case 5:
			if (processSteps?.length) {
				let lastCompletedStatus = 1;
				for (const step of processSteps) {
					if (step.status === 5) break;
					if (step.status !== 5 && step.status > lastCompletedStatus) {
						lastCompletedStatus = step.status;
					}
				}
				const statusToStepMap: Record<number, number> = { 1: 1, 2: 2, 3: 3, 4: 4 };
				completedStep = statusToStepMap[lastCompletedStatus] ?? 1;
				if (lastCompletedStatus === 3) {
					rejectStep = 4;
				} else if (lastCompletedStatus === 2) {
					rejectStep = 3;
				} else if (lastCompletedStatus === 4) {
					rejectStep = 5;
				} else {
					rejectStep = 2;
				}
			} else {
				if (isInbound) {
					if (row.firstApprovalTime && row.firstApprovalStatus === 2) {
						rejectStep = 2;
						completedStep = 1;
					} else if (row.secondApprovalTime && row.secondApprovalStatus === 2) {
						rejectStep = 3;
						completedStep = 2;
					} else if (row.finalExecutionTime && row.finalExecutionStatus === 2) {
						rejectStep = 4;
						completedStep = 3;
					}
				} else if (isOutbound) {
					if (row.firstApprovalTime && row.firstApprovalStatus === 2) {
						rejectStep = 2;
						completedStep = 1;
					} else if (row.secondApprovalTime && row.secondApprovalStatus === 2) {
						rejectStep = 3;
						completedStep = 2;
					} else if (row.finalExecutionTime && row.finalExecutionStatus === 2) {
						rejectStep = 4;
						completedStep = 3;
					}
				}
				if (!rejectStep) rejectStep = Math.min(completedStep + 1, stepCount);
			}
			activeStep = rejectStep || Math.min(2, stepCount);
			break;
		default:
			break;
	}

	for (let idx = 0; idx < stepCount; idx++) {
		const stepNumber = idx + 1;
		if (idx === 0) {
			statuses[idx] = 'finish';
			continue;
		}
		if (approvalAction === 5 && rejectStep === stepNumber) {
			statuses[idx] = 'error';
		} else if (stepNumber <= completedStep) {
			statuses[idx] = 'finish';
		} else if (approvalAction !== 5 && stepNumber === activeStep) {
			statuses[idx] = 'process';
		} else {
			statuses[idx] = 'wait';
		}
	}

	for (let idx = 0; idx < connectors.length; idx++) {
		const currentStatus = statuses[idx];
		const nextStatus = statuses[idx + 1];
		connectors[idx] =
			currentStatus === 'finish' || nextStatus === 'finish' || nextStatus === 'process' || nextStatus === 'error';
	}

	for (let idx = 0; idx < stepCount; idx++) {
		const title = steps[idx]?.title || `第${idx + 1}步`;
		const status = statuses[idx];
		let suffix = '等待中';
		if (status === 'finish') suffix = '已完成';
		else if (status === 'error') suffix = '已拒绝';
		else if (status === 'process') suffix = '进行中';
		tooltips[idx] = `${title} - ${suffix}`;
	}

	const finishCount = statuses.filter((s) => s === 'finish').length;
	const errorCount = statuses.filter((s) => s === 'error').length;
	let summary = `待审批(${finishCount}/${stepCount})`;

	if (errorCount > 0) {
		summary = `已拒绝(${errorCount}/${stepCount})`;
	} else if (finishCount === stepCount) {
		summary = `已完成(${finishCount}/${stepCount})`;
	} else {
		const processIndex = statuses.findIndex((s) => s === 'process');
		if (processIndex >= 0) {
			const title = steps[processIndex]?.title || '';
			const stageName = stageNameMap[title] || (title ? `待${title}` : '待审批');
			summary = `${stageName}(${finishCount}/${stepCount})`;
		}
	}

	return { steps, statuses, connectors, tooltips, summary };
};

const getFlowMeta = (row: any): FlowMeta => {
	if (!row.__flowMeta) {
		row.__flowMeta = computeFlowMeta(row);
	}
	return row.__flowMeta as FlowMeta;
};

const getFlowSteps = (row: any): FlowStep[] => getFlowMeta(row).steps;


// 获取表格中步骤状态
const getTableStepStatus = (row: any, stepNumber: number) => {
	const meta = getFlowMeta(row);
	return meta.statuses[stepNumber - 1] ?? (stepNumber === 1 ? 'finish' : 'wait');
};

// 获取表格中步骤样式类
const getTableStepClass = (row: any, stepNumber: number) => {
	const status = getTableStepStatus(row, stepNumber);
	return `mini-step-${status}`;
};

// 获取步骤提示信息
const getStepTooltip = (row: any, stepNumber: number) => {
	const meta = getFlowMeta(row);
	return meta.tooltips[stepNumber - 1] ?? '';
};

// 获取连接线状态
const getConnectorStatus = (row: any, currentStep: number, nextStep: number) => {
	const meta = getFlowMeta(row);
	return Boolean(meta.connectors[currentStep - 1]);
};

// 获取审批进度摘要文本
const getProgressSummary = (row: any) => {
	if (!row) return '无流程';
	return getFlowMeta(row).summary;
};

// 查看详情
const viewDetail = (row: any) => {
	detailDialogRef.value?.openDialog(row);
};

	// 批量审批
const handleBatchApproval = (action: 'approve' | 'reject') => {
	if (isActionLocked.value) {
		ElMessage.warning('正在处理中，请稍候');
		return;
	}
	if (state.selectData.length === 0) {
		ElMessage.warning('请先选择要审批的项目');
		return;
		}

		// 直接利用后端下发的可操作标记过滤
		const approvalItems = state.selectData.filter((item) => {
			const { canApprove, canReject } = resolveOperationFlags(item);
			return action === 'approve' ? canApprove : canReject;
		});

	if (approvalItems.length === 0) {
		ElMessage.warning('所选项目中没有可审批的项目');
		return;
	}

	// 如果有部分项目不可审批，给出提示
	if (approvalItems.length < state.selectData.length) {
		const nonApprovalCount = state.selectData.length - approvalItems.length;
		ElMessage.info({
			message: `已过滤掉 ${nonApprovalCount} 个不可审批项目，将对 ${approvalItems.length} 个项目执行批量${action === 'approve' ? '同意' : '拒绝'}操作`,
			duration: 3000,
		});
	}

	batchApprovalDialogRef.value?.openDialog(approvalItems, action);
};

// 处理批量审批提交
const handleBatchApprovalSubmit = async (data: any) => {
	// 防重复提交：若正在执行，则忽略本次请求
	if (isBatchSubmitting.value) {
		ElMessage.warning('正在执行批量审批，请勿重复点击');
		return;
	}
	isBatchSubmitting.value = true;
	try {
		const { action, items } = data;
		const actionText = action === 'approve' ? '同意' : '拒绝';

		let successCount = 0;
		let failCount = 0;
		const errors: string[] = [];

		const worker = async (item: any) => {
			try {
				const allowAdminDirectApprove =
					action === 'approve'
						? item.canAdminDirectApprove ?? legacyCanDirectApprove(item)
						: false;

				if (allowAdminDirectApprove && (!item.confirmerId || item.confirmerId <= 0)) {
					throw new Error('直接审批必须指定发放确认人');
				}

				const computedNextStatus =
					action === 'approve'
						? item.nextApprovalAction ?? legacyGetNextApprovalStatus(item)
						: 5;
				if (action === 'approve' && (computedNextStatus === undefined || computedNextStatus === null)) {
					throw new Error('当前节点无法继续推进');
				}

				const nextStatus = computedNextStatus ?? item.approvalAction;
				const nextQuantity = action === 'approve' ? item.approvedQuantity || item.quantity : item.quantity;
				const normalizedQuantity = nextQuantity !== undefined && nextQuantity !== null ? Number(nextQuantity) : nextQuantity;
				const nextTotal = action === 'approve' ? calculateMaterialTotal(item, normalizedQuantity as number | undefined) : item.materialPriceTotal;

				const updateData = {
					id: item.id,
					flowType: item.flowType,
					batchNo: item.batchNo,
					requestNo: item.requestNo,
					storeTypeId: item.storeTypeId,
					storeTypeName: item.storeTypeName,
					materialId: item.materialId,
					materialName: item.materialName,
					materialPrice: item.materialPrice,
					quantity: normalizedQuantity,
					unit: item.unit,
					materialPriceTotal: nextTotal,
					applicantId: item.applicantId,
					applicantName: item.applicantName,
					applicantDept: item.applicantDept,
					receiverId: item.receiverId,
					receiverName: item.receiverName,
					receiverDept: item.receiverDept,
					requestTime: item.requestTime,
					expectedDate: item.expectedDate,
					completedTime: item.completedTime,
					statusNewOrChange: item.statusNewOrChange,
					approvalAction: nextStatus,
					remark: item.remark || `批量${actionText}`,
					confirmerId: action === 'approve' ? item.confirmerId || null : null,
					confirmerName: action === 'approve' ? item.confirmerName || '' : '',
					adminDirectApprove: allowAdminDirectApprove || undefined,
				};

				await storeProcessFlowStepApi.update(updateData);
				successCount++;
			} catch (error: any) {
				failCount++;
				const errorMsg = error?.response?.data?.message || error?.message || '未知错误';
				errors.push(`${item.requestNo}: ${errorMsg}`);
			}
		};

		const queue = [...items];
		const concurrency = 5;
		while (queue.length > 0) {
			const chunk = queue.splice(0, concurrency);
			await Promise.all(chunk.map(worker));
		}

	// 显示结果
	if (successCount > 0) {
		ElMessage.success(`批量${actionText}完成：成功 ${successCount} 个${failCount > 0 ? `，失败 ${failCount} 个` : ''}`);
	}

	if (failCount > 0 && errors.length > 0) {
		// 显示详细错误信息
		ElMessageBox.alert(errors.slice(0, 5).join('\n') + (errors.length > 5 ? '\n...' : ''), '批量操作失败详情', { type: 'error' });
	}

	// 清空选择并刷新列表
	state.selectData = [];
	// 审批后切换到按“更新时间”降序，方便核对最新审批记录
	const refreshParams = state.activeTab === 'allApprovals'
		? { field: 'updateTime', order: 'descending' }
		: {};
	handleQuery(refreshParams);
} catch (error) {
	console.error('批量审批失败:', error);
	ElMessage.error('批量审批失败，请重试');
} finally {
	isBatchSubmitting.value = false;
	}
};

// 格式化货币显示
const formatCurrency = (amount: number) => {
	if (amount >= 10000) {
		return (amount / 10000).toFixed(1) + '万';
	}
	return amount.toLocaleString();
};

// 获取预算进度条颜色
const getBudgetProgressColor = (usageRate: number) => {
	if (usageRate >= 90) return '#f56c6c'; // 红色 - 危险
	if (usageRate >= 70) return '#e6a23c'; // 橙色 - 警告
	return '#67c23a'; // 绿色 - 正常
};

// 加载预算信息
const loadBudgetInfo = async () => {
	// 只在"待我审批"标签页并且是出库申请时加载预算
	if (state.activeTab !== 'myPending') {
		state.budgetInfo = null;
		return;
	}

	// 检查当前页面是否有出库申请
	const outboundItems = state.tableData.filter((item: any) => item.flowType === '出库');
	if (outboundItems.length === 0) {
		state.budgetInfo = null;
		return;
	}

	// 检查是否有选中的出库项目
	const selectedOutboundItems = state.selectData.filter((item: any) => item.flowType === '出库');
	if (selectedOutboundItems.length === 0) {
		state.budgetInfo = null;
		return;
	}

	try {
		state.budgetLoading = true;

		// 使用看板数据API获取所有预算信息
		const dashboardResult = await storeBudgetConfigApi.getDashboardData();

		if (dashboardResult.data?.result?.budgetDetails) {
			const allBudgets = dashboardResult.data.result.budgetDetails;

			// 收集所有选中项目涉及的区域
			const orgIds = new Set<number>();
			selectedOutboundItems.forEach((item: any) => {
				const orgId = item.orgId || item.OrgId;
				if (orgId) orgIds.add(orgId);
			});

			// 为每个区域查找预算并汇总
			let totalBudget = 0;
			let totalUsed = 0;
			let totalPending = 0;
			let selectedAmount = 0;
			let foundBudget = false;

			for (const orgId of orgIds) {
				// 查找该区域的预算
				let budgetData = allBudgets.find((budget: any) => budget.orgsId === orgId || budget.OrgsId === orgId);

				// 如果没找到，尝试通过部门名称匹配
				if (!budgetData) {
					const item = selectedOutboundItems.find((i: any) => (i.orgId || i.OrgId) === orgId);
					if (item?.applicantDept) {
						const deptName = item.applicantDept;

						if (deptName === '沪南') {
							budgetData = allBudgets.find((budget: any) => (budget.orgName && budget.orgName.includes('曲面组立')) || (budget.OrgName && budget.OrgName.includes('曲面组立')));
						}

						if (!budgetData) {
							budgetData = allBudgets.find((budget: any) => {
								const orgName = budget.orgName || budget.OrgName || '';
								return orgName && (orgName.includes('曲面组立') || orgName.includes('作业区') || deptName.includes(orgName) || orgName.includes(deptName));
							});
						}
					}
				}

				if (budgetData) {
					foundBudget = true;
					const budgetTotal = budgetData.totalAmount || budgetData.TotalAmount || 0;
					const budgetUsed = budgetData.usedAmount || budgetData.UsedAmount || 0;
					const budgetPending = budgetData.pendingAmount || budgetData.PendingAmount || 0;

					totalBudget += budgetTotal;
					totalUsed += budgetUsed;
					totalPending += budgetPending;
				}
			}

			// 计算选中项目的总金额
			selectedAmount = selectedOutboundItems.reduce((sum: number, item: any) => {
				return sum + (item.materialPriceTotal || 0);
			}, 0);

			if (foundBudget) {
				const currentUsed = totalUsed + totalPending;
				const afterApprovalUsed = currentUsed + selectedAmount;
				const remainingBudget = totalBudget - currentUsed;
				const afterApprovalRemaining = totalBudget - afterApprovalUsed;
				const usageRate = totalBudget > 0 ? (currentUsed / totalBudget) * 100 : 0;
				const afterApprovalRate = totalBudget > 0 ? (afterApprovalUsed / totalBudget) * 100 : 0;

				state.budgetInfo = {
					totalAmount: totalBudget,
					usedAmount: totalUsed,
					pendingAmount: totalPending,
					currentUsed: currentUsed,
					remainingAmount: remainingBudget,
					usageRate: usageRate,
					selectedAmount: selectedAmount,
					afterApprovalUsed: afterApprovalUsed,
					afterApprovalRemaining: afterApprovalRemaining,
					afterApprovalRate: afterApprovalRate,
				};
			} else {
				state.budgetInfo = null;
			}
		} else {
			state.budgetInfo = null;
		}
	} catch (error) {
		console.error('加载预算信息失败:', error);
		state.budgetInfo = null;
	} finally {
		state.budgetLoading = false;
	}
};
</script>
<template>
	<div class="storeProcessFlowStep-container" v-loading="state.exportLoading">
		<splitpanes class="default-theme">
			<!-- 左侧物资分类树 -->
			<pane size="12">
				<StoreTypeTree ref="storeTypeTreeRef" :data="state.storeTypeTreeData" @node-click="handleCategoryChange" @refresh="loadStoreTypeTree" />
			</pane>

			<!-- 右侧审批流程表格 -->
			<pane size="88" class="right-container">
				<!-- 整个右侧容器，使用flex布局 -->
				<div class="right-content">
					<!-- 顶部Tabs卡片 -->
					<el-card shadow="hover" :body-style="{ paddingBottom: '0' }" class="tabs-card">
						<el-tabs v-model="state.activeTab" @tab-click="(tab: any) => handleTabChange(tab.name)" class="approval-tabs">
							<el-tab-pane label="待我审批" name="myPending">
								<template #label>
									<span class="tab-label">
										<el-icon><ele-Clock /></el-icon>
										待我审批
									</span>
								</template>
							</el-tab-pane>
							<el-tab-pane label="全部审批" name="allApprovals">
								<template #label>
									<span class="tab-label">
										<el-icon><ele-List /></el-icon>
										全部审批
									</span>
								</template>
							</el-tab-pane>
						</el-tabs>

						<el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90" class="query-form">
							<el-row>
								<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
									<el-form-item label="关键字">
										<el-input v-model="state.tableQueryParams.keyword" clearable placeholder="请输入申请号/物资名称" />
									</el-form-item>
								</el-col>
								<el-col v-if="state.showAdvanceQueryUI && state.activeTab === 'myPending'" :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
									<el-form-item label="申请人区域">
										<el-select v-model="state.tableQueryParams.orgId" clearable placeholder="请选择申请人区域" @change="handleQuery">
											<el-option v-for="org in orgOptions" :key="org.id" :label="org.name" :value="org.id" />
										</el-select>
									</el-form-item>
								</el-col>
								<el-col v-if="state.showAdvanceQueryUI" :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
									<el-form-item label="类型">
										<el-select v-model="state.tableQueryParams.flowType" clearable placeholder="全部">
											<el-option label="入库" value="入库" />
											<el-option label="出库" value="出库" />
										</el-select>
									</el-form-item>
								</el-col>
								<el-col v-if="state.showAdvanceQueryUI && state.activeTab === 'allApprovals'" :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
									<el-form-item label="审批状态">
										<el-select v-model="state.tableQueryParams.approvalAction" clearable placeholder="全部">
											<el-option label="待审核" :value="1" />
											<el-option label="已审核" :value="2" />
											<el-option label="已审批" :value="3" />
											<el-option label="已完成" :value="4" />
											<el-option label="已拒绝" :value="5" />
										</el-select>
									</el-form-item>
								</el-col>
								<el-col v-if="state.showAdvanceQueryUI" :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
									<el-form-item label="申请人">
										<el-input v-model="state.tableQueryParams.applicantName" clearable placeholder="请输入申请人姓名" />
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
									<el-form-item>
										<el-button-group style="display: flex; align-items: center">
											<el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'storeProcessFlowStep:page'" v-reclick="1000"> 查询 </el-button>
										<el-button
											icon="ele-Refresh"
											@click="
												() => {
													const includeArchived = state.activeTab === 'allApprovals' ? false : undefined;
													state.tableQueryParams = includeArchived === undefined ? {} : { includeArchived };
													handleQuery();
												}
											"
										>
											重置
										</el-button>
											<el-button
												icon="ele-ZoomIn"
												@click="
													() => {
														state.showAdvanceQueryUI = true;
													}
												"
												v-if="!state.showAdvanceQueryUI"
											>
												高级查询
											</el-button>
											<el-button
												icon="ele-ZoomOut"
												@click="
													() => {
														state.showAdvanceQueryUI = false;
													}
												"
												v-if="state.showAdvanceQueryUI"
											>
												隐藏
											</el-button>
											<el-dropdown v-if="state.activeTab === 'myPending'" :show-timeout="70" :hide-timeout="50" @command="exportStoreProcessFlowStepCommand" style="margin-left: 5px">
												<el-button type="primary" icon="ele-FolderOpened" v-reclick="20000" v-auth="'storeProcessFlowStep:export'"> 导出 </el-button>
												<template #dropdown>
													<el-dropdown-menu>
														<el-dropdown-item command="select" :disabled="state.selectData.length == 0">导出选中</el-dropdown-item>
														<el-dropdown-item command="current">导出本页</el-dropdown-item>
														<el-dropdown-item command="all">导出全部</el-dropdown-item>
													</el-dropdown-menu>
												</template>
											</el-dropdown>
												<el-button
													v-if="showBatchApprovalButton"
													type="success"
													style="margin-left: 5px"
													icon="ele-CircleCheck"
													:disabled="state.selectData.length === 0 || isActionLocked"
													@click="handleBatchApproval('approve')"
												>
												批量审批{{ state.selectData.length > 0 ? ` (${state.selectData.length})` : '' }}
											</el-button>
											<el-button
												v-if="state.activeTab === 'allApprovals'"
												type="danger"
												style="margin-left: 5px"
												icon="ele-Delete"
												@click="batchDelStoreProcessFlowStep"
												:disabled="state.selectData.length == 0"
												v-auth="'storeProcessFlowStep:batchDelete'"
											>
												删除
											</el-button>
											<el-button
												v-if="state.activeTab === 'allApprovals'"
												type="primary"
												style="margin-left: 5px"
												icon="ele-Plus"
												@click="editDialogRef.openDialog(null, '新增审批流程')"
												v-auth="'storeProcessFlowStep:add'"
											>
												新增
											</el-button>
										</el-button-group>
									</el-form-item>
								</el-col>
							</el-row>
						</el-form>
					</el-card>

					<!-- 表格卡片 -->
					<el-card shadow="hover" class="table-card" :style="{ marginTop: '8px', minHeight: tableCardMinHeight }">
						<!-- 价格汇总统计区域 -->
						<div class="summary-section" v-if="state.tableData.length > 0">
							<div class="summary-card">
								<div class="summary-item">
									<span class="summary-label">当前页面总价:</span>
									<span class="summary-value total-amount">￥{{ totalAmount.toFixed(2) }}</span>
								</div>
								<div class="summary-item">
									<span class="summary-label">记录数量:</span>
									<span class="summary-value">{{ state.tableData.length }} 条</span>
								</div>
								<div class="summary-item" v-if="state.selectData.length > 0">
									<span class="summary-label">已选择:</span>
									<span class="summary-value selected-amount">￥{{ selectedAmount.toFixed(2) }} ({{ state.selectData.length }}条)</span>
								</div>
								<!-- 预算进度条 - 只在待我审批且有选中出库项目时显示 -->
								<div class="summary-item summary-item--budget budget-progress-item" v-if="state.activeTab === 'myPending' && state.budgetInfo && !state.budgetLoading">
									<div class="budget-info-compact">
										<div class="budget-stats">
											<span class="budget-label-mini">本次选择:</span>
											<span class="budget-value-mini">￥{{ formatCurrency(state.budgetInfo.selectedAmount) }}</span>
											<span class="budget-separator">|</span>
											<span class="budget-label-mini">剩余额度:</span>
											<span
												class="budget-value-mini"
												:class="{ 'budget-warning': state.budgetInfo.afterApprovalRate >= 90, 'budget-alert': state.budgetInfo.afterApprovalRate >= 70 && state.budgetInfo.afterApprovalRate < 90 }"
											>
												￥{{ formatCurrency(state.budgetInfo.afterApprovalRemaining) }}
											</span>
											<span class="budget-separator">|</span>
											<span class="budget-label-mini">总额度:</span>
											<span class="budget-value-mini">￥{{ formatCurrency(state.budgetInfo.totalAmount) }}</span>
										</div>
										<el-progress :percentage="state.budgetInfo.afterApprovalRate" :color="getBudgetProgressColor(state.budgetInfo.afterApprovalRate)" :stroke-width="6" class="budget-progress-bar">
											<template #default="{ percentage }">
												<span class="progress-text">{{ percentage.toFixed(1) }}%</span>
											</template>
										</el-progress>
									</div>
								</div>
								<!-- 预算加载状态 -->
								<div class="summary-item summary-item--budget" v-if="state.activeTab === 'myPending' && state.budgetLoading">
									<el-icon class="is-loading" style="margin-right: 4px"><ele-Loading /></el-icon>
									<span class="budget-label-mini">加载预算...</span>
								</div>
							</div>
						</div>
						<el-table
							:data="state.tableData"
							@selection-change="
								(val: any[]) => {
									state.selectData = val;
									loadBudgetInfo();
								}
							"
							:height="tableHeight"
							style="width: 100%"
							v-loading="state.tableLoading"
							tooltip-effect="light"
							row-key="id"
							@sort-change="sortChange"
							border
							:virtualized="enableVirtualScroll"
							:scrollbar-always-on="enableVirtualScroll"
							:estimated-row-height="60"
						>
							<el-table-column type="selection" width="40" align="center" fixed="left" v-if="auth('storeProcessFlowStep:batchDelete') || auth('storeProcessFlowStep:update')" />
							<el-table-column type="index" label="序号" width="55" align="center" fixed="left" />
							<el-table-column prop="flowType" label="类型" width="60" align="center" fixed="left" show-overflow-tooltip>
								<template #default="scope">
									<el-tag :type="scope.row.flowType === '入库' ? 'success' : 'warning'">{{ scope.row.flowType }}</el-tag>
								</template>
							</el-table-column>
							<!-- <el-table-column prop="requestNo" label="申请号" width="160" show-overflow-tooltip /> -->
							<el-table-column label="申请价格" width="90" fixed="left" align="right" show-overflow-tooltip>
								<template #default="scope">
									<span class="total-price">￥{{ scope.row.materialPriceTotal?.toFixed(2) || '0.00' }}</span>
								</template>
							</el-table-column>
							<el-table-column prop="storeTypeDisplayName" label="分类" width="150" show-overflow-tooltip />
							<el-table-column prop="materialName" label="物资名称" width="180" show-overflow-tooltip />
							<el-table-column label="申请信息" width="120" align="center" show-overflow-tooltip>
								<template #default="scope">
									<div class="approval-info">{{ scope.row.quantity }} {{ scope.row.unit }}</div>
								</template>
							</el-table-column>
							<el-table-column prop="statusNewOrChange" label="新增/更换" width="100" align="center" show-overflow-tooltip>
								<template #default="scope">
									<el-tag :type="scope.row.statusNewOrChange === 1 ? 'success' : 'warning'" size="small">
										<g-sys-dict v-model="scope.row.statusNewOrChange" code="StatusNewOrChangeEnum" />
									</el-tag>
								</template>
							</el-table-column>
							<el-table-column prop="applicantName" label="申请人" width="100" fixed="left" show-overflow-tooltip />
							<el-table-column prop="receiverName" label="接收人" width="100" show-overflow-tooltip />
							<el-table-column prop="requestTime" label="申请时间" width="150" show-overflow-tooltip>
								<template #default="scope">
									{{ scope.row.requestTime ? scope.row.requestTime.split(' ')[0] : '' }}
								</template>
							</el-table-column>
							<el-table-column prop="approvalAction" label="审批状态" width="100" align="center" show-overflow-tooltip>
								<template #default="scope">
									<el-tag :type="getStatusTagType(scope.row.approvalAction)">
										<g-sys-dict v-model="scope.row.approvalAction" code="StatusApprovalEnum" />
									</el-tag>
								</template>
							</el-table-column>
							<el-table-column label="审批进度" width="120" align="center" fixed="left">
								<template #default="scope">
									<el-popover placement="right" :width="280" trigger="hover">
										<template #default>
											<div class="table-flow-progress-detail">
												<div style="font-size: 12px; margin-bottom: 8px; color: #666">{{ getProgressSummary(scope.row) }}</div>
												<div class="flow-steps-mini">
													<div v-for="(step, index) in getFlowSteps(scope.row)" :key="index" class="mini-step-item" :class="getTableStepClass(scope.row, index + 1)">
														<div class="mini-step-icon" :title="getStepTooltip(scope.row, index + 1)">
															<span v-if="getTableStepStatus(scope.row, index + 1) === 'finish'" class="step-check">✓</span>
															<span v-else-if="getTableStepStatus(scope.row, index + 1) === 'error'" class="step-error">✗</span>
															<span v-else class="step-short">{{ step.short }}</span>
														</div>
														<div
															v-if="index < getFlowSteps(scope.row).length - 1"
															class="mini-step-connector"
															:class="{ 'connector-active': getConnectorStatus(scope.row, index + 1, index + 2) }"
														></div>
													</div>
												</div>
											</div>
										</template>
										<template #reference>
												<div class="flow-steps-mini">
													<div v-for="(step, index) in getFlowSteps(scope.row)" :key="index" class="mini-step-item" :class="getTableStepClass(scope.row, index + 1)">
														<div class="mini-step-icon" :title="getStepTooltip(scope.row, index + 1)">
															<span v-if="getTableStepStatus(scope.row, index + 1) === 'finish'" class="step-check">✓</span>
															<span v-else-if="getTableStepStatus(scope.row, index + 1) === 'error'" class="step-error">✗</span>
															<span v-else class="step-short">{{ step.short }}</span>
														</div>
														<div
															v-if="index < getFlowSteps(scope.row).length - 1"
															class="mini-step-connector"
															:class="{ 'connector-active': getConnectorStatus(scope.row, index + 1, index + 2) }"
														></div>
													</div>
												</div>
										</template>
									</el-popover>
								</template>
							</el-table-column>
							<el-table-column prop="confirmerName" label="当前审批人" width="120" show-overflow-tooltip>
								<template #default="scope">
									<span v-if="scope.row.approvalAction === 5" style="color: #f56c6c">{{ scope.row.confirmerName }}</span>
									<span v-else>{{ scope.row.confirmerName }}</span>
								</template>
							</el-table-column>
							<el-table-column label="审批操作" width="200" align="center" fixed="right" show-overflow-tooltip>
								<template #default="scope">
									<div class="action-buttons">
										<!-- 显示审批按钮的条件（已集成权限判断） -->
										<template v-if="shouldShowApprovalButtons(scope.row)">
												<el-tooltip effect="dark" :content="getApprovalButtonText(scope.row)" placement="top">
													<el-button
														icon="ele-Check"
														size="small"
														circle
														type="success"
														class="icon-only-btn"
														:disabled="isActionLocked"
														@click="handleApproval(scope.row)"
													/>
												</el-tooltip>
												<el-tooltip effect="dark" :content="getRejectButtonText(scope.row)" placement="top">
													<el-button
														icon="ele-Close"
														size="small"
														circle
														type="danger"
														class="icon-only-btn"
														:disabled="isActionLocked"
														@click="handleApproval(scope.row, 5)"
													/>
												</el-tooltip>
											<el-tooltip
												v-if="canReturnToPreviousStep(scope.row)"
												effect="dark"
												:content="getReturnButtonText(scope.row)"
												placement="top"
											>
													<el-button
														icon="ele-RefreshLeft"
														size="small"
														circle
														type="warning"
														plain
														class="icon-only-btn"
														:disabled="isActionLocked"
														@click="handleReturn(scope.row)"
													/>
											</el-tooltip>
										</template>
										<!-- 无权限或已完成状态显示结果 -->
										<template v-else>
											<el-tag :type="getApprovalTagType(scope.row.approvalAction)">
												{{ getApprovalTagText(scope.row.approvalAction) }}
											</el-tag>
										</template>
										<!-- 查看详情和删除 -->
										<el-button icon="ele-View" size="small" text type="primary" @click="viewDetail(scope.row)">详情</el-button>
										<el-button icon="ele-Delete" size="small" text type="danger" @click="delStoreProcessFlowStep(scope.row)" v-auth="'storeProcessFlowStep:delete'">删除</el-button>
									</div>
								</template>
							</el-table-column>
						</el-table>
						<el-pagination
							v-model:currentPage="state.tableParams.page"
							v-model:page-size="state.tableParams.pageSize"
							@size-change="(val: any) => handleQuery({ pageSize: val })"
							@current-change="(val: any) => handleQuery({ page: val })"
							layout="total, sizes, prev, pager, next, jumper"
							:page-sizes="[10, 20, 50, 100, 200, 500]"
							:total="state.tableParams.total"
							size="small"
							background
						/>
					</el-card>

					<printDialog ref="printDialogRef" :title="'打印审批流程'" @reloadTable="handleQuery" />
					<editDialog ref="editDialogRef" @reloadTable="handleQuery" />
					<approvalDialog ref="approvalDialogRef" @submit="handleApprovalSubmit" />
					<detailDialog ref="detailDialogRef" />
					<batchApprovalDialog ref="batchApprovalDialogRef" @submit="handleBatchApprovalSubmit" />
				</div>
			</pane>
		</splitpanes>
	</div>
</template>
<style scoped>
:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}

/* Tabs样式 */
.approval-tabs {
	margin-bottom: 20px;
}

.tab-label {
	display: flex;
	align-items: center;
	gap: 6px;
	font-weight: 500;
}

.query-form {
	padding: 0;
}

.query-form :deep(.el-form-item) {
	margin-bottom: 0;
}

.query-form :deep(.el-form-item__content) {
	width: 100%;
}

:deep(.el-tabs__header) {
	margin: 0 0 20px 0;
}

:deep(.el-tabs__nav-wrap::after) {
	height: 1px;
	background-color: #e4e7ed;
}

:deep(.el-tabs__active-bar) {
	height: 3px;
	background-color: #409eff;
}

:deep(.el-tabs__item.is-active) {
	color: #409eff;
	font-weight: 600;
}

:deep(.el-tabs__item) {
	padding: 0 20px;
	font-size: 14px;
}

/* 表格样式优化 */
:deep(.el-table) {
	font-size: 13px;
}

:deep(.el-table th) {
	background-color: #f8f9fa;
	color: #606266;
	font-weight: 600;
}

/* 审批操作区域样式 */
:deep(.el-table td) {
	vertical-align: middle;
}

/* 表格中的流程进度样式 */
.table-flow-progress {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 4px;
}

.flow-steps-mini {
	display: flex;
	align-items: center;
	gap: 3px;
	justify-content: center;
	flex-wrap: wrap;
	padding: 4px 0;
}

.table-flow-progress-detail {
	padding: 8px;
}

.mini-step-item {
	display: flex;
	align-items: center;
	position: relative;
}

.mini-step-icon {
	width: 18px;
	height: 18px;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-weight: 400;
	font-size: 12px;
	flex-shrink: 0;
	transition: all 0.3s ease;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.mini-step-connector {
	display: none;
}

.connector-active {
	background-color: #67c23a;
}

/* 不同状态的迷你步骤样式 */
.mini-step-wait .mini-step-icon {
	background-color: #f0f2f5;
	color: #909399;
	border: 1px solid #e4e7ed;
}

.mini-step-process .mini-step-icon {
	background-color: #409eff;
	color: #ffffff;
	border: 1px solid #409eff;
	animation: mini-pulse 2s infinite;
}

.mini-step-finish .mini-step-icon {
	background-color: #67c23a;
	color: #ffffff;
	border: 1px solid #67c23a;
}

.mini-step-error .mini-step-icon {
	background-color: #f56c6c;
	color: #ffffff;
	border: 1px solid #f56c6c;
}

@keyframes mini-pulse {
	0% {
		box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.4);
	}
	50% {
		box-shadow: 0 0 0 4px rgba(64, 158, 255, 0.1);
	}
	100% {
		box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
	}
}

/* 当前审批人拒绝信息样式 */
.reject-info {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 2px;
}

.reject-label {
	font-size: 11px;
	color: #f56c6c;
	background-color: #fef0f0;
	padding: 1px 4px;
	border-radius: 3px;
	border: 1px solid #fbc4c4;
}

.mt-1 {
	margin-top: 4px;
}

/* 审批操作按钮容器 */
.action-buttons {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 4px;
	flex-wrap: nowrap;
}

.action-buttons .el-button {
	margin: 0;
}

.icon-only-btn {
	padding: 0 !important;
	min-width: 0 !important;
	width: 26px;
	height: 26px;
}

.action-buttons .el-tag {
	margin-right: 4px;
}

/* 审批按钮样式 */
:deep(.el-button--small) {
	padding: 4px 8px;
	font-size: 12px;
}

/* 标签样式 */
:deep(.el-tag) {
	font-weight: 500;
}

/* 申请信息样式 */
.approval-info {
	font-weight: 500;
	color: #303133;
}

/* 价格信息样式 */
.price-info {
	text-align: right;
}

.total-price {
	font-weight: 600;
	font-size: 14px;
	color: #e6a23c;
	margin-bottom: 2px;
}

.unit-info {
	font-size: 12px;
	color: #909399;
}

/* 批量审批下拉菜单样式 */
:deep(.el-dropdown) {
	.el-button {
		position: relative;

		&:hover {
			transform: translateY(-1px);
			box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
		}
	}
}

:deep(.el-dropdown-menu__item) {
	padding: 8px 16px;

	&:hover {
		background-color: #f5f7fa;
		color: #409eff;
	}

	.el-icon {
		margin-right: 8px;
	}
}

/* 汇总统计区域样式 */
.summary-section {
	display: flex;
	align-items: center;
	margin-bottom: 16px;
	padding: 10px 18px;
	background-color: var(--el-fill-color-light);
	border-radius: var(--el-border-radius-base);
	border: 1px solid var(--el-border-color-extra-light);
	box-shadow: var(--el-box-shadow-lighter);
	overflow-x: auto;
}

.summary-card {
	display: flex;
	gap: 20px;
	align-items: center;
	flex-wrap: nowrap;
	white-space: nowrap;
	width: 100%;
}

.budget-progress-item {
	flex: 0 0 auto;
}

.budget-info-compact {
	display: flex;
	align-items: center;
	gap: 12px;
	padding: 0 12px;
	min-height: 24px;
	background-color: var(--el-fill-color-blank);
	border-radius: var(--el-border-radius-base);
	border: 1px solid var(--el-border-color-lighter);
	box-shadow: var(--el-box-shadow-light);
	white-space: nowrap;
}

.budget-stats {
	display: flex;
	align-items: center;
	gap: 8px;
	font-size: 13px;
	flex-wrap: nowrap;
}

.budget-label-mini {
	color: var(--el-text-color-secondary);
	font-size: 12px;
}

.budget-value-mini {
	font-weight: 600;
	color: var(--el-text-color-primary);
	font-size: 13px;
}

.budget-separator {
	color: var(--el-border-color-extra-light);
	margin: 0 4px;
}

.budget-warning {
	color: var(--el-color-danger) !important;
}

.budget-alert {
	color: var(--el-color-warning) !important;
}

.budget-progress-bar {
	margin-top: 0;
	width: 180px;
	flex-shrink: 0;
}

.progress-text {
	font-size: 11px;
	font-weight: 600;
}

.summary-item {
	display: flex;
	align-items: center;
	flex-shrink: 0;
	position: relative;
	padding-right: 20px;
	min-height: 24px;
	box-sizing: border-box;
}

.summary-item::after {
	content: '';
	position: absolute;
	right: 10px;
	top: 50%;
	transform: translateY(-50%);
	width: 1px;
	height: 16px;
	background-color: var(--el-border-color-lighter);
	opacity: 0.8;
}

.summary-item:last-of-type::after,
.summary-item.summary-item--budget::after {
	display: none;
}

.summary-item.summary-item--budget {
	padding-right: 0;
}

.summary-item.summary-item--budget .budget-info-compact {
	min-height: 24px;
}

.summary-label,
.summary-value,
.budget-label-mini,
.budget-value-mini {
	line-height: 24px;
}

.summary-label {
	font-size: 14px;
	color: var(--el-text-color-regular);
	font-weight: 500;
}

.summary-value {
	font-size: 14px;
	font-weight: 600;
	color: var(--el-text-color-primary);
}

.total-amount {
	color: var(--el-color-warning);
	font-size: 16px;
}

.selected-amount {
	color: var(--el-color-success);
	font-size: 15px;
}

/* 分屏布局样式 */
.storeProcessFlowStep-container {
	height: calc(100vh - 84px);
}

/* Splitpanes 根组件高度 */
:deep(.splitpanes) {
	height: 100%;
}

:deep(.splitpanes__pane) {
	overflow: hidden !important;
	height: 100% !important;
	display: flex !important;
	flex-direction: column !important;
}

/* 左侧面板允许滚动（物资分类树可能很长） */
:deep(.splitpanes__pane:first-child) {
	overflow: auto !important;
}

:deep(.splitpanes__splitter) {
	background-color: var(--el-border-color-light);
	position: relative;
	opacity: 0.7;
}

:deep(.splitpanes__splitter:hover) {
	opacity: 1;
	background-color: var(--el-color-primary);
}

/* 右侧容器 - 由splitpanes pane组件使用 */
.right-container {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}

/* 右侧内容区域 - flex布局容器 */
.right-content {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}

/* Tabs和查询表单卡片 */
.tabs-card {
	flex-shrink: 0;
	margin-bottom: 8px;
	overflow-y: auto;
	border-bottom: 1px solid var(--el-border-color-light);
	max-height: 25vh;
}

.tabs-card :deep(.el-card__body) {
	padding: 12px 16px;
}

/* 表格卡片 - 占据剩余所有空间 */
.table-card {
	flex: 1;
	display: flex;
	flex-direction: column;
	overflow: hidden;
	min-height: 0;
	width: 100%;
}

.table-card :deep(.el-card) {
	height: 100% !important;
	display: flex !important;
	flex-direction: column !important;
	overflow: hidden !important;
}

.table-card :deep(.el-card__body) {
	display: flex !important;
	flex-direction: column !important;
	flex: 1 !important;
	overflow: hidden !important;
	padding: 12px 12px 0 12px !important;
	height: 100% !important;
	min-height: 0 !important;
	gap: 0 !important;
}

/* 汇总统计区域 */
.summary-section {
	flex-shrink: 0;
	margin-bottom: 8px;
	padding-bottom: 0;
	border-bottom: none;
	max-height: 50px;
	overflow: auto;
	height: auto;
}

/* 表格容器包装器 - 占据剩余空间 */
.table-card :deep(.el-table) {
	flex: 1 !important;
	overflow: hidden !important;
	border: none !important;
	width: 100% !important;
	min-height: 0 !important;
	display: flex !important;
	flex-direction: column !important;
}

.table-card :deep(.el-table__inner-wrapper) {
	display: flex !important;
	flex-direction: column !important;
	overflow: hidden !important;
	width: 100% !important;
	height: 100% !important;
}

.table-card :deep(.el-table__header-wrapper) {
	flex-shrink: 0 !important;
	height: auto !important;
	width: 100% !important;
	overflow: hidden !important;
}

.table-card :deep(.el-table__body-wrapper) {
	flex: 1 !important;
	overflow-y: auto !important;
	overflow-x: auto !important;
	width: 100% !important;
	min-height: 0 !important;
}

.table-card :deep(.el-table__body) {
	width: 100% !important;
}

/* 分页器 */
.table-card :deep(.el-pagination) {
	flex-shrink: 0;
	padding: 12px 0 12px 0;
	margin: 0;
	border-top: 1px solid var(--el-border-color-light);
	display: flex !important;
	justify-content: flex-end !important;
	align-items: center !important;
}
</style>
